using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace Melis.Chat.HttpHandler
{
	class Base : IHttpHandler
	{
		private HttpContext _context;
		public string UserName
		{
			get
			{
				if ((HttpContext.Current.Session != null) && (string.IsNullOrEmpty(HttpContext.Current.Session["UserName"].ToString())))
					return Convert.ToString(this ._context.Session["UserName"]);
				else
				{
					string tmpUser = "Guest" + DateTime.Now.ToString("s");
					UserName = tmpUser;

					return tmpUser;
				}
			}
			set
			{
				try
				{ this._context.Session["UserName"] = value; }
				catch { }
			}
		}

		#region IHttpHandler Members

		public virtual bool IsReusable
		{
			get { return true; }
		}

		public virtual void ProcessRequest(HttpContext context)
		{
			this._context = context;
			context.Response.Expires = 0;
			context.Response.AddHeader("cache-control", "no-cache");

			context.Response.ContentType = "text/plain";
			string operation = context.Request["op"].ToUpper();
			string clientID = context.Request["id"];
			string msg = context.Request["t"];
			string text = Convert.ToString(context.Application["MelisChat" + clientID]);

			context.Response.Write(operation);
			context.Response.Write(clientID + "\n");
			if (operation == "R")//Refresh
			{
				context.Response.Write(text);
			}
			else if (operation == "M")//Refresh
			{
				text += UserName + " says: " + msg + "<br/>\n";
				context.Response.Write(text);
			}

			context.Application["MelisChat" + clientID] = text;
		}

		#endregion
	}
}
